package com.example.mapper;

import com.example.dto.BorrowRecordDTO;
import com.example.pojo.Borrow;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface BorrowMapper {


    // 1. 查询所有借阅记录
    @Select("SELECT * FROM tbl_borrow")
    List<Borrow> findAll();

    // 2. 更新借阅状态（0：未归还，1：已归还）
    @Update("UPDATE tbl_borrow SET status = 1,return_date=#{returnDate} WHERE id = #{id}")
    boolean updateStatus(Integer id, String returnDate);

    //3.新建借阅记录
    @Insert("INSERT INTO tbl_borrow (user_id, book_id, borrow_date, return_date, status) " +
            "VALUES (#{userId}, #{bookId}, #{borrowDate}, #{returnDate}, #{status})")
    Boolean insertBorrow(Borrow borrow);


    @Select("""
                SELECT b.id, u.username, bk.name AS bookName, b.borrow_date AS borrowDate,
                       b.return_date AS returnDate, b.status
                FROM tbl_borrow b
                LEFT JOIN tbl_user u ON b.user_id = u.id
                LEFT JOIN tbl_book bk ON b.book_id = bk.id
                WHERE (#{keyword} IS NULL OR #{keyword} = ''
                       OR u.username LIKE CONCAT('%', #{keyword}, '%')
                       OR bk.name LIKE CONCAT('%', #{keyword}, '%'))
                ORDER BY b.borrow_date DESC
                LIMIT #{offset}, #{pageSize}
            """)
    List<BorrowRecordDTO> searchBorrows(@Param("keyword") String keyword,
                                        @Param("offset") int offset,
                                        @Param("pageSize") int pageSize);


    @Select("""
                SELECT COUNT(*)
                FROM tbl_borrow b
                LEFT JOIN tbl_user u ON b.user_id = u.id
                LEFT JOIN tbl_book bk ON b.book_id = bk.id
                WHERE (#{keyword} IS NULL OR #{keyword} = ''
                       OR u.username LIKE CONCAT('%', #{keyword}, '%')
                       OR bk.name LIKE CONCAT('%', #{keyword}, '%'))
            """)
    int countBorrows(@Param("keyword") String keyword);
}
